<template>
  <div class="code-container" ref="codeContainer"></div>
</template>
<script>
import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
//代码高亮
import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution";
// 引入查找控件
import "monaco-editor/esm/vs/editor/contrib/find/findController.js";
export default {
  name: "",
  props: {},
  components: {},
  computed: {},
  data() {
    return {
      code: "",
    };
  },
  created() {},
  mounted() {
    this.init();
    // this.setPrompt();
  },
  methods: {
    init() {
      this.editor = monaco.editor.create(this.$refs.codeContainer, {
        value: "", //编辑器初始显示文字
        theme: "vs", //vs-dark是黑色的背景 vs是白色的背景  官方自带三种主题vs, hc-black, or vs-dark
        autoIndex: true,
        overviewRulerBorder: true,
        language: "javascript", // 语言
        fontSize: "15px",
        //   height: "500px",

        automaticLayout: true, // 自动布局
        minimap: {
          // 关闭小地图
          enabled: true,
        },
        //   lineNumbers: "off", // 隐藏控制行号
      });
      //实时获取编辑器的值
      this.editor.onDidChangeModelContent(() => {
        this.code = this.editor.getValue();
      });
    },
    //设置错误提示
    setPrompt() {
      const model = this.editor.getModel();
      // json为语言类型
      monaco.editor.setModelMarkers(model, "json", [
        {
          startLineNumber: 2,
          endLineNumber: 2,
          startColumn: 1,
          endColumn: 10,
          severity: monaco.MarkerSeverity.Error,
          message: `语法错误`,
        },
      ]);
    },
    // 获取编辑框内容
    getCodeContext() {
      return this.editor.getValue();
    },
    // 自动格式化代码
    format() {
      this.editor.trigger("anything", "editor.action.formatDocument");
      // 或者
      // this.editor.getAction(['editor.action.formatDocument']).run()
    },
    changeEditor() {
      if (this.editor === null) {
        this.init();
      }

      const oldModel = this.editor.getModel();
      const newModel = monaco.editor.createModel(this.code, "javascript");

      if (oldModel) {
        oldModel.dispose();
      }
      this.editor.setModel(newModel);
    },
  },
  watch: {},
};
</script>
<style lang="scss" scoped>
.code-container {
  height: calc(100% - 95px);
  padding: 10px 0;
}
</style>
